package com.cloud.code.算法;

import org.junit.Test;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCache<K,V> implements Iterable<K>{

    final static int MAX = 3;

    LinkedHashMap<K,V> linkedHashMap = new LinkedHashMap<K, V>();

    public void cache(K key,V value){

        if(linkedHashMap.containsKey(key)){
            linkedHashMap.remove(key);
        }else if(linkedHashMap.size() >= MAX){
            Iterator<K> iterator = linkedHashMap.keySet().iterator();
            K first = iterator.next();
            linkedHashMap.remove(first);
        }

        linkedHashMap.put(key,value);
    }

    @Override
    public Iterator<K> iterator() {
        Iterator<Map.Entry<K, V>> iterator = linkedHashMap.entrySet().iterator();
        return new Iterator<K>() {
            @Override
            public boolean hasNext() {
                return iterator.hasNext();
            }

            @Override
            public K next() {
                return iterator.next().getKey();
            }
        };
    }

    @Test
    public void test(){
        LRUCache<Integer,String> lruCache = new LRUCache();
        lruCache.cache(1,"1111");
        lruCache.cache(2,"2222");
        lruCache.cache(3,"3333");
        System.out.println(lruCache);
        lruCache.cache(2,"2222");
    }
}
